
package com.project.projectA.core.dao;

import java.io.Serializable;

import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.UUIDHexGenerator;

/**
 * hibernate 主键生成策略.
 *
 * @author wuwei
 */
public class UIDGenerator extends UUIDHexGenerator {

	/* (non-Javadoc)
	 * @see org.hibernate.id.UUIDHexGenerator#generate(org.hibernate.engine.SessionImplementor, java.lang.Object)
	 */
	@Override
	public Serializable generate(SessionImplementor session, Object object) {
		return new StringBuilder(16).append(formatShort(getAppId())).append(format(getHiTime()))
				.append(format(getLoTime())).append(formatShort(getCount())).toString();
	}

	/**
	 * Generate.
	 *
	 * @return the string
	 */
	public String generate() {
		return (String) generate(null, null);
	}

	/**
	 * 可重载子类实现从System Properties, Spring ApplicationContext等地方获得值.
	 *
	 * @return the app id
	 */
	protected short getAppId() {
		return 0;
	}

	/**
	 * 格式化最大值为255的数值成长度为2的字符串.
	 *
	 * @param value the value
	 * @return the string
	 */
	protected String formatShort(short value) {
		String formatted = Integer.toHexString(value);
		if (formatted.length() < 2) {
			formatted = "0" + formatted;
		}
		return formatted;
	}

}
